
import 'dart:ffi';
import 'dart:io';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:network_info_plus/network_info_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/utils/logs.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';
import 'package:smart_freezer/generated/locale_keys.g.dart';
import 'package:ty_smart_home/ty_smart_home.dart';

import '../../../core/utils/color_util.dart';
import '../../../core/utils/local_storage.dart';


class LCWIFIPage extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<LCWIFIPage> {
  
  bool isSelected = false;
  var _ssidController = TextEditingController();
  var _pwdController = TextEditingController();

  static const EventChannel _channel = const EventChannel('ty_smart_home_event');

  bool isDarkMode = LocalStorage.getThemeMode() == 1;

  @override
  void initState() {
    super.initState();

    // 获取WIFI名称
    // TySmartHome.getWIFIName().then((value) {
    //   _ssidController.text = value;
    // });

    // TyEventChannel.receiveStream().listen(_onData);
    _channel.receiveBroadcastStream().listen(_onData);

    _getWIFIName();

  }

  _getWIFIName() async {
    final _networkInfo = NetworkInfo();

    String? wifiBSSID = "";
    if (Platform.isIOS) {
      LocationAuthorizationStatus status = await _networkInfo.getLocationServiceAuthorization();
      if (status == LocationAuthorizationStatus.notDetermined) {
        status = await _networkInfo.requestLocationServiceAuthorization();
      }
      if (status == LocationAuthorizationStatus.authorizedAlways || status == LocationAuthorizationStatus.authorizedWhenInUse) {
        wifiBSSID = await _networkInfo.getWifiName();
      } else {
        logs('location service is not authorized, the data might not be correct');
        wifiBSSID = await _networkInfo.getWifiName();
      }
    } else {
      wifiBSSID = await _networkInfo.getWifiName();
    }

    final result = wifiBSSID?.replaceAll("\"", "");
    setState(() {
      _ssidController.text = result ?? "获取失败";
    });

  }

  _onData(event){
    if(!mounted) return;

    setState(() {
      // wifiResult = event;
      isSelected = false;

      if (event == "1") {  // 配网成功
        // SmartDialog.showToast("WIFI connect success");
      } else {
        // SmartDialog.showToast("Try again"); // WIFI connect fail,
        print("eventData: ${event}");
      }
    });

    // 提示配网成功/失败
    Future.delayed(Duration(seconds: 1)).then((value) {
      showOkAlertDialog(
        context: context,
        message: event == "1" ? "WIFI connect success" : "WIFI connect fail, try again",
        barrierDismissible: false,
        useActionSheetForIOS: true,
        onWillPop: () async { return false;},
        builder: (context, child) => Theme(
          data: ThemeData(
              primarySwatch: createMaterialColor(isDarkMode ? Colors.white : Colors.black),
              dialogBackgroundColor: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
              colorScheme: ColorScheme(
                primary: isDarkMode ? Colors.white : Colors.black, // 文字颜色
                primaryVariant: Colors.white,
                secondary: Colors.green,
                background: Colors.white,
                error: Colors.red,
                brightness: isDarkMode ? Brightness.dark : Brightness.light,    /// 最最关键
                onBackground: Colors.pink,
                secondaryVariant: Colors.white,
                onError: Colors.yellow,
                onPrimary: Colors.red, //顶部栏字体颜色
                onSecondary: Colors.black,
                onSurface: Colors.white,   // 导航栏字体颜色, 返回按钮颜色
                surface: MainCommon.darkBlueMaterialColor,  // 导航栏背景颜色
              )),
          child: child,
        ),
      ).then((value) {
        if(event == "1"){
          Get.offNamed(LCRouter.home);
        }
      });
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.4,
        title: Text(LocaleKeys.wifi_title.trc(), ), // style: TextStyle(color: Colors.black),
        centerTitle: true,
        // backgroundColor: Colors.white,
        leading: InkWell(
          onTap: () => Get.back(),
            child: Icon(Icons.arrow_back_ios, )
        ),
      ),
      body: Container(
        // color: Colors.grey[50],
        child: Card(
          margin: EdgeInsets.all(15),
          child: Container(
            width: double.infinity,
            padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: double.infinity,
                    padding: EdgeInsets.fromLTRB(0, 0, 0, 10),
                    child: Text(LocaleKeys.wifi_device_tip.trc(),
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                    )
                  ),

                  // Text("1. Power on the device", style: TextStyle(fontSize: 16),),
                  // SizedBox(height: 10,),
                  // Text("2. Hold the RESET button on the back of the device for 5 secons until the icon rapidly blinks"
                  //     , style: TextStyle(fontSize: 16)),
                  // SizedBox(height: 10,),
                  // Text("3. Enter your WIFI name and password"
                  //     , style: TextStyle(fontSize: 16)),

                  Text(
                      LocaleKeys.wifi_config_method.trc(),
                      style: TextStyle(fontSize: 15)),

                  Container(
                    width: double.infinity,
                    padding: EdgeInsets.fromLTRB(10, 20, 10, 0),
                    child: Column(
                      children: [
                        Stack(
                          children: [
                            TextField(
                              style: TextStyle(color: Colors.black),
                              controller: _ssidController,
                              // readOnly: true,    // 不可编辑
                              cursorColor: Colors.grey,
                              decoration: InputDecoration(
                                  icon: Icon(Icons.wifi, color: context.isDarkMode ? Colors.white : Colors.grey,),
                                  // labelText: "username",
                                  hintText: LocaleKeys.wifi_wifi_name.trc(),
                                  border: InputBorder.none,
                                  filled: true,
                                  fillColor: Colors.grey[50]
                              ),
                              onSubmitted: (value) {
                                print("onSubmitted:$value");
                              },
                            ),

                            Positioned(
                                right: 0,
                                top: 0,
                                child: TextButton(
                                  child: Text(LocaleKeys.wifi_change_net.trc(), style: TextStyle(color: Colors.blue),),
                                  onPressed: () {
                                    TySmartHome.go2WIFISetting();
                                  },
                                ),
                            ),
                          ],
                        ),


                        SizedBox(height: 1,),
                        TextField(
                          style: TextStyle(color: Colors.black),
                          controller: _pwdController,
                          cursorColor: Colors.grey,
                          decoration: InputDecoration(
                              icon: Icon(Icons.work_outline, color: context.isDarkMode ? Colors.white : Colors.grey,),
                              // labelText: "username",
                              hintText: LocaleKeys.wifi_wifi_pwd.trc(),
                              border: InputBorder.none,
                              filled: true,
                              fillColor: Colors.grey[50],
                          ),
                          onSubmitted: (value) {
                            print("onSubmitted:$value");
                          },
                        ),

                        SizedBox(height: 10,),
                        Container(
                          width: double.infinity,
                          height: 44,
                          child: TextButton(
                            style: ButtonStyle(
                              backgroundColor: MaterialStateProperty.resolveWith((states) {
                                if(states.contains(MaterialState.disabled)) {
                                  return Colors.grey;
                                }
                                return Color(0xFF2973B4);
                              }),
                              shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(20))),
                            ),
                            child: Text(LocaleKeys.add_device_confirm.trc(), style: TextStyle(fontSize: 18, color: Colors.white),),
                            onPressed: isSelected ? null : confirmClick,  // null 为按钮禁用状态
                          ),
                        ),

                        // isSelected ? ConnectingWidget() : Text(""),

                        SizedBox(height: 10,),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  void startConfigWIFI() async {
    final homeID = await TySmartHome.getHomeID();
    // final ssid = await TySmartHome.getWIFIName();
    // _ssidController.text = ssid;

    if (_ssidController.text.isNotEmpty && _pwdController.text.isNotEmpty) {
      TySmartHome.commitEZModeAction(homeID, _ssidController.text, _pwdController.text);
    }
  }

  confirmClick() {
    print("点击了配网按钮");
    if (_ssidController.text.length > 0 && _pwdController.text.length > 0) {
      setState(() {
        isSelected = !isSelected;
      });
      // 开始配网
      startConfigWIFI();
    } else {
      SmartDialog.showToast("SSID or password cannot be empty");
    }

    // return () {
    //   print("点击了配网按钮");
    //   if (_ssidController.text.length > 0 && _pwdController.text.length > 0) {
    //     setState(() {
    //       isSelected = !isSelected;
    //     });
    //     // 开始配网
    //     startConfigWIFI();
    //   } else {
    //     SmartDialog.showToast("SSID or password cannot be empty");
    //   }
    //
    // };
  }

}

class ConnectingWidget extends StatelessWidget {
  const ConnectingWidget({
    Key? key,
  }) : super(key: key);



  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
      // color: Colors.red,
      child: Column(
        children: [
          CircularProgressIndicator(
            color: context.isDarkMode ? Colors.white : MainCommon.darkBlueMaterialColor,
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("1. find the device"), // Connecting
                Text("2. register the device"),
                Text("3. initialize the device"),
              ],
            )
          ),
        ],
      ),
    );
  }
}
